package com.joyveb.securitycheck.util;

import java.security.MessageDigest;
import java.util.zip.CRC32;

import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

public class HashComponent {

	private HashComponent() {
	}

	public static final String KEY_SHA = "SHA";
	public static final String KEY_SHA_256 = "SHA-256";
	public static final String KEY_SHA_224 = "SHA-224";
	public static final String KEY_SHA_384 = "SHA-384";
	public static final String KEY_SHA_512 = "SHA-512";
	public static final String KEY_MD5 = "MD5";

	
	public static byte[] md5(byte[] data) throws Exception {
		return HashComponent.encrypt(data, KEY_MD5);
	}

	public static byte[] sha(byte[] data) throws Exception {
		return HashComponent.encrypt(data, KEY_SHA);
	}
	
	public static byte[] sha256(byte[] data) throws Exception {
		return HashComponent.encrypt(data, KEY_SHA_256);
	}
	
	public static boolean sha256verify(byte[] sign,byte[] data)throws Exception {
		return ByteUtils.equals(sign, HashComponent.encrypt(data, KEY_SHA_256));
	}
	
	
	public static byte[] sha224(byte[] data) throws Exception {
		return HashComponent.encrypt(data, KEY_SHA_224);
	}
	
	public static byte[] sha384(byte[] data) throws Exception {
		return HashComponent.encrypt(data, KEY_SHA_384);
	}
	
	public static byte[] sha512(byte[] data) throws Exception {
		return HashComponent.encrypt(data, KEY_SHA_512);
	}
	
	public static byte[] crc32sign(byte[] data) {
		CRC32 crc32 = new CRC32();
		crc32.update(data);
		String s =  Long.toHexString(crc32.getValue());
		return StringUtils.leftPad(s, 8, "0").getBytes();
	}
	public static boolean crc32verify(byte[] sign,byte[] data){
		CRC32 crc32 = new CRC32();
		crc32.update(data);
		String s =  Long.toHexString(crc32.getValue());
		String _sign =  StringUtils.leftPad(s, 8, "0");
		return ByteUtils.equals(sign, _sign.getBytes());
	}
	
	private static byte[] encrypt(byte[] data,String key) throws Exception {
		MessageDigest sha = MessageDigest.getInstance(key);
		sha.update(data);
		return sha.digest();
	}

}
